﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace App
{
    public class LinearRegression
    {
        public LinearRegression(double[] xValues, double[] yValues)
        {
            Solve(xValues, yValues);
        }

        public Dictionary<string, double> Result { get; private set; }

        private double SumForSimpleArray(double[] values)
        {
            return values.Sum();
        }

        private double SumForXy(double[] xValues, double[] yValues)
        {
            return xValues.Select((t, i) => t*yValues[i]).Sum();
        }

        private double SumForQuadraticArray(double[] values)
        {
            return values.Select(t => Math.Pow(t, 2)).Sum();
        }

        private void Solve(double[] xValues, double[] yValues)
        {
            var sumXy = (SumForXy(xValues, yValues)/xValues.Length)*2;
            var sumY = (SumForSimpleArray(yValues)/xValues.Length)*2;
            var sumX2 = SumForQuadraticArray(xValues)/xValues.Length;
            var sumX = (SumForSimpleArray(xValues)/xValues.Length)*2;

            var a = ((2*sumXy) - (sumX*sumY))/(((2*(sumX2*2)) - (sumX*sumX)));
            var b = ((sumY) - (sumX)*(a))/2;

            Result = new Dictionary<string, double>
            {
                {"a", a},
                {"b", b}
            };
        }
    }
}